import { useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { request } from '@/request';
import { useHistory } from 'react-router-dom';
import { useEnter } from '@/hooks';

const Login = () => {
   const emailRef = useRef<HTMLInputElement>(null);
   const pwdRef = useRef<HTMLInputElement>(null);
   const [msg, setMsg] = useState('');
   let history = useHistory();

   const handleSubmit = () => {
      const email = emailRef.current?.value;
      const password = pwdRef.current?.value;
      // 验证
      if (!email || !password) {
         setMsg('请输入邮箱和密码');
         return;
      }
      request('/auth/login', {
         method: 'POST',
         data: {
            email,
            password,
         },
         showSuccess: true,
         success: (data) => {
            localStorage.setItem('token', data.token);
            localStorage.setItem('username', data.username);
            location.href='/'
         },
      });
      setMsg('');
   };
   useEnter(handleSubmit);
   return (
      <main className="full bg-slate-400">
         <div className="box max-w-sm mx-auto mt-48">
            <h2 className="text-center mb-4">Login</h2>
            <form>
               <div className="form-item">
                  <div className="form-item-content">
                     <label className='w-1/3'>Email</label>
                     <input ref={emailRef} name="email" autoFocus />
                  </div>
               </div>

               <div className="form-item">
                  <div className="form-item-content">
                     <label className='w-1/3'>Password</label>
                     <input ref={pwdRef} name="password" />
                  </div>
               </div>
               {msg && <p className="form-item-msg">{msg}</p>}
            </form>
            <div className="text-center mt-4">
               <button className="w-full" onClick={handleSubmit}>
                  Submit
               </button>
            </div>
            <div className="text-center text-xs my-3">
               <span>还没有账号？</span>
               <Link to="/register">点击注册</Link>
            </div>
         </div>
      </main>
   );
};

export default Login;
